import 'dart:io';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/page/page_main.dart';
import 'package:wu_you/page/splash/page_splash.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/route/app_routers.dart';
import 'package:wu_you/route/app_routes_import.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:platform/platform.dart';

void main() {
  runApp(
    MultiBlocProvider(
      providers: [
        //首页索引
        BlocProvider.value(value: MainIndexCubit()),
      ],
      child: MyApp(),
    ),
  );
  Platform plat = LocalPlatform();
  if (plat.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    WebView.platform = SurfaceAndroidWebView();
  }
}

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  //setLocale 方法用于从应用的任何位置切换语言环境。它通过找到最近的 _MyAppState 实例，并调用其 setLocale 方法来实现切换语言功能。
  static void setLocale(BuildContext context, Locale newLocale) {
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>();
    state.setLocale(newLocale);
  }
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Color _themeColor = AppColors.primaryColor;

  Locale _locale = const Locale('zh', ''); // 默认语言为中文
//_loadLocaleFromPreferences 方法从 SharedPreferences 中加载用户偏好设置的语言环境。如果存在保存的语言代码，就将其更新到 _locale 变量中。
  Future<void> _loadLocaleFromPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String languageCode = prefs.getString('languageCode');
    if (languageCode != null) {
      setState(() {
        _locale = Locale(languageCode, '');
      });
    }
  }

  //_saveLocaleToPreferences 方法用于将选择的语言环境保存到 SharedPreferences 中，以便下次启动应用时可以加载该语言环境。
  Future<void> _saveLocaleToPreferences(Locale locale) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('languageCode', locale.languageCode);
  }

  void setLocale(Locale newLocale) {
    _saveLocaleToPreferences(newLocale);
    setState(() {
      _locale = newLocale;
    });
  }
  @override
  void initState() {
    super.initState();
    _loadLocaleFromPreferences();
  }

  @override
  Widget build(BuildContext context) {
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    final routes  = AppRoutesImport.routes;
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      onGenerateRoute: (RouteSettings settings) {
        // 获取声明的路由页面函数
        var pageBuilder = routes[settings.name];

        if (pageBuilder != null) {
          if (settings.arguments != null) {
            // 创建路由页面并携带参数
            return MaterialPageRoute(
                builder: (context) =>
                    pageBuilder(context, arg:settings.arguments));
          } else {
            return MaterialPageRoute(
                builder: (context) => pageBuilder(context));
          }
        }
        return MaterialPageRoute(builder: (context) => MainPage());
      },
      home: SplashPage(),
      builder: (context, child) {
        return MediaQuery(
          //设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: GestureDetector(
            onTap: () {
              FocusScopeNode currentFocus = FocusScope.of(context);
              if (!currentFocus.hasPrimaryFocus &&
                  currentFocus.focusedChild != null) {
                FocusManager.instance.primaryFocus.unfocus();
              }
            },
            child: child,
          ),
        );
      },
      navigatorKey: AppGlobalKeys.navigatorKey,
      theme: ThemeData.light().copyWith(
        primaryColor: _themeColor,
        accentColor: _themeColor,
        indicatorColor: Colors.white,
        dividerTheme: DividerThemeData(
          color: AppColors.dividerColor,
          space: 1,
        ),
        hintColor: AppColors.textHintColor,
        buttonColor: AppColors.primaryColor,
        textSelectionTheme: TextSelectionThemeData(
          cursorColor: AppColors.primaryColor,
        ),
        unselectedWidgetColor: Colors.grey,
        dialogTheme: DialogTheme(
          backgroundColor: Colors.white,
          titleTextStyle: TextStyle(fontSize: 16, color: AppColors.textColor),
          contentTextStyle: TextStyle(fontSize: 14, color: AppColors.textColor),
        ),
        textButtonTheme: TextButtonThemeData(
          style: ButtonStyle(
            textStyle: MaterialStateProperty.all(TextStyle(fontSize: 14)),
            foregroundColor: MaterialStateProperty.resolveWith(
              (states) => AppColors.textColor,
            ),
            backgroundColor: MaterialStateProperty.resolveWith(
                (states) => AppColors.transparent),
            //设置水波纹颜色
            overlayColor: MaterialStateProperty.all(Colors.white54),
            alignment: Alignment.center,
          ),
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ButtonStyle(
            textStyle: MaterialStateProperty.all(TextStyle(fontSize: 14)),
            //前景色，文本、图标颜色
            foregroundColor: MaterialStateProperty.resolveWith(
              (states) => Colors.white,
            ),
            //背景颜色，按钮颜色
            backgroundColor: MaterialStateProperty.resolveWith((states) {
              //默认颜色
              return AppColors.primaryColor;
            }),
            alignment: Alignment.center,
            //设置水波纹颜色
            overlayColor:
                MaterialStateProperty.all(AppColors.buttonPressedColor),
            //设置阴影  不适用于这里的TextButton
            elevation: MaterialStateProperty.all(2),
            //设置按钮内边距
            padding: MaterialStateProperty.all(EdgeInsets.all(0)),
            //设置按钮的大小
            minimumSize: MaterialStateProperty.all(Size.fromHeight(48)),
            //外边框装饰 会覆盖 side 配置的样式
            shape: MaterialStateProperty.all(StadiumBorder()),
          ),
        ),
        textTheme: TextTheme(
          button: TextStyle(fontSize: 12, color: Colors.white),
          caption: TextStyle(fontSize: 14, color: Colors.white),
          overline: TextStyle(fontSize: 8, color: Colors.white),
          headline1: TextStyle(fontSize: 12, color: Colors.white),
          headline2: TextStyle(fontSize: 14, color: Colors.white),
          headline3: TextStyle(fontSize: 16, color: Colors.white),
          headline4: TextStyle(fontSize: 12, color: AppColors.textColor),
          headline5: TextStyle(fontSize: 14, color: AppColors.textColor),
          headline6: TextStyle(fontSize: 16, color: AppColors.textColor),
          subtitle1: TextStyle(fontSize: 12, color: AppColors.textHintColor),
          subtitle2: TextStyle(fontSize: 8, color: AppColors.textHintColor),
          bodyText1: TextStyle(fontSize: 14, color: AppColors.textHintColor),
          bodyText2: TextStyle(fontSize: 14, color: AppColors.textColor),
        ),
        buttonTheme: ButtonThemeData(
          buttonColor: _themeColor,
          textTheme: ButtonTextTheme.primary,
          splashColor: AppColors.splashColor,
          hoverColor: AppColors.splashColor,
        ),
        toggleableActiveColor: _themeColor,
        appBarTheme: AppBarTheme(
          color: _themeColor,
          brightness: Brightness.dark,
          iconTheme: IconThemeData(
            color: Colors.white,
          ),
          centerTitle: true,
          elevation: 0,
          actionsIconTheme: IconThemeData(
            color: Colors.white,
            size: 24,
          ),
        ),
        bottomNavigationBarTheme: BottomNavigationBarThemeData(
          elevation: 4,
          unselectedItemColor: AppColors.textHintColor,
          showUnselectedLabels: true,
          selectedItemColor: AppColors.primaryColor,
          type: BottomNavigationBarType.fixed,
        ),
        scaffoldBackgroundColor: AppColors.backgroundColor,
        floatingActionButtonTheme: FloatingActionButtonThemeData(
          backgroundColor: AppColors.primaryColor,
        ),
        progressIndicatorTheme: ProgressIndicatorThemeData(
          color: AppColors.primaryColor
        )
      ),
      //国际语言包
      localizationsDelegates: [
        AppLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        DefaultCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('en', ''),
        Locale('zh', ''),
      ],
      locale: _locale
    );
  }
}
